package com.zg.autoform.web;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zg.autoform.vo.ConditionUpdateVo;
import com.zg.common.core.A;
import com.zg.common.core.R;
import com.zg.common.core.dao.autoform.*;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * @author Zxb
 */
@RestController
@RequiredArgsConstructor
@Api(tags = "表单数据管理")
public class ZxbConditionController {
    private final DiyFormDao formDao;
    private final DiyColumnDao columnDao;
    private final DiyConditionDao conditionDao;

    @GetMapping("/zxb/condition/list")
    public R searchCondition(Long formId) {
        List<DiyColumn> columnList = columnDao.list(new QueryWrapper<DiyColumn>()
                .lambda()
                .eq(DiyColumn::getFormId, formId));
        List<DiyCondition> conditionList = conditionDao.list(new QueryWrapper<DiyCondition>()
                .lambda()
                .eq(DiyCondition::getFormId, formId));
        return R.success(Arrays.asList(columnList, conditionList));
    }

    @GetMapping("/zxb/condition/view")
    public R viewCondition(String formCode) {
        DiyForm form = formDao.getOne(
                new LambdaQueryWrapper<DiyForm>()
                        .eq(DiyForm::getCode, formCode)
        );
        A.isInDatabase(form, "表单");
        List<DiyCondition> conditionList = conditionDao.list(new QueryWrapper<DiyCondition>()
                .lambda()
                .eq(DiyCondition::getFormId, form.getId()));
        return R.success(conditionList);
    }

    @PostMapping("/zxb/condition/update")
    public R updateCondition(@RequestBody ConditionUpdateVo conditionUpdateVo) {
        Long formId = conditionUpdateVo.getFormId();
        //删除原来字段布局
        conditionDao.remove(new QueryWrapper<DiyCondition>()
                .lambda()
                .eq(DiyCondition::getFormId, formId));
        List<DiyCondition> conditionList = conditionUpdateVo.getConditionList();
        conditionDao.saveBatch(conditionList);
        return R.success(conditionList.size());
    }
}
